package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.mapper.RoleMapper;
import com.ktjiaoyu.crm.mapper.RoleRightMapper;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.realm.MyShiroRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName : RoleServiceImpl
 * @Description :
 * @Author : Lzz
 * @Date: 2023/11/22 10:33:35
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleRightMapper roleRightMapper;

    @Cacheable(cacheNames = "role",key = "'roleList'",unless = "#result == null")
    @Override
    public List<Role> findAllRoleList() {

        return roleMapper.selectList(null);
    }


    /**
     * 新增用户的同时保存权限信息
     * @param role
     * @param rightCodes
     * @return
     */
    @CacheEvict(cacheNames = "role",key = "'roleList'")
    @Transactional
    @Override
    public boolean saveRoleAndRight(Role role, String[] rightCodes) {
        //第一步：保存角色信息
        boolean resultOk = this.saveOrUpdate(role);
        //如果新增成功角色，则将权限信息也一起存入数据库中
        if(resultOk && role.getRoleId()!=null){
            //第二步：先删除旧的角色权限
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("rf_role_id",role.getRoleId());
            roleRightMapper.delete(updateWrapper);
        }
        //第三步：保存新的角色权限
        boolean roleRightOk = true;
        if(rightCodes!=null && rightCodes.length!=0){
            roleRightOk = roleRightMapper.saveRoleRight(role,rightCodes);
        }
        //清空所有用户权限缓存
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();
        return resultOk && roleRightOk;
    }

    /**
     * 根据用户ID查询该用户所拥有角色
     * @param usrId
     * @return
     */
    @Override
    public Role findRoleByUserId(Long usrId) {
        return roleMapper.findRoleByUserId(usrId);
    }
}
